﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MvvmTest.Db;
using MvvmTest.Models;
using MvvmTest.Views;

namespace MvvmTest.ViewModels;

public partial class MainViewModel : ObservableObject
{
    private readonly LocalDb _localDb;
    
    // public RelayCommand QueryCommand { get; set; }
    // public RelayCommand ResetCommand { get; set; }
    // int 表示带入参数的类型
    // public RelayCommand<int> EditCommand { get; set; }
    // public RelayCommand<int> DelCommand { get; set; }
    // public RelayCommand AddCommand { get; set; }

    [ObservableProperty] private string _search = string.Empty;

    [ObservableProperty] private BindingList<Student> _gridModelList;

    public MainViewModel()
    {
        _localDb = new LocalDb();
        // QueryCommand=new RelayCommand(Query);
        // ResetCommand=new RelayCommand(() =>
        // {
        //     Search=string.Empty;
        //     this.Query();
        // });
        // 初始化
        // EditCommand = new RelayCommand<int>(t => Edit(t));
        // DelCommand = new RelayCommand<int>(t => Del(t));
        // AddCommand = new RelayCommand(Add);
    }
    [RelayCommand]
    private void Query()
    {
        var models = _localDb.GetStudentsByName(Search);
        GridModelList = new BindingList<Student>();
        if (models != null)
        {
            models.ForEach(arg => { GridModelList.Add(arg); });
        }
    }

    [RelayCommand]
    public void Edit(int id)
    {
        var studentById = _localDb.GetStudentById(id);
        if (studentById!= null)
        {
            UserView view = new UserView(studentById);
            var r = view.ShowDialog();
            if (r.Value)
            {
                var newModel = GridModelList.FirstOrDefault(t => t.Id == studentById.Id);
                if (newModel!= null)
                {
                    newModel.Name = studentById.Name;
                }
            }
        }
    }

    [RelayCommand]
    public void Del(int id)
    {
        var model = _localDb.GetStudentById(id);
        if (model!=null)
        {
            var r = MessageBox.Show($"确认删除当前用户:{model.Name}?", "操作提示", MessageBoxButton.OK, MessageBoxImage.Question);
            if (r==MessageBoxResult.OK)
            {
                _localDb.DeleteStudent(model.Id);
                this.Query();
            }
        }
    }
    
    [RelayCommand]
    public void Add()
    {
        Student student = new Student();

        UserView view = new UserView(student);
        var r = view.ShowDialog();
        if (r.Value)
        {
            student.Id = GridModelList.Max(t => t.Id) + 1;
            _localDb.AddStudent(student);
            this.Query();
        }
    }

    [RelayCommand]
    public void Reset()
    {
        Search=string.Empty;
        this.Query();
    }
}